package com.vast.admin.api.cietac.config;

import com.vast.admin.api.cietac.entity.CietacToken;
import com.vast.admin.api.cietac.feign.CietacTokenApi;
import com.vast.system.exception.BusinessException;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

@Slf4j
public class CietacFeignConfig implements RequestInterceptor {

    @Autowired
    private CietacTokenApi cietacTokenApi;

    private static CietacToken cietacToken;

    /**
     * 上次获取token时间
     */
    private static long prevTokenTime;

    @Value("${cietac.client_id}")
    private String clientId;

    @Value("${cietac.client_secret}")
    private String clientSecret;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        log.info("调用贸仲接口：{}, 参数：{}, RequestBody：{}", requestTemplate.path(), requestTemplate.queries(), requestTemplate.requestBody().asString());
		requestTemplate.header("Authorization", "Bearer " + getToken());
    }

    private String getToken() {
        initCietacToken();
        return cietacToken.getAccess_token();
    }

    private void initCietacToken() {
        //判断token是否为空
        if (cietacToken == null) {
            synchronized (this) {
                if (cietacToken == null) {
                    cietacToken = cietacTokenApi.token(clientId, clientSecret, "client_credentials");
                    if (cietacToken == null || StringUtils.isBlank(cietacToken.getAccess_token())) {
                        throw new BusinessException("贸仲TOKEN获取失败");
                    }
                    prevTokenTime = System.currentTimeMillis();
                }
            }
        } else {
            //不为空时判断token是否过期
            if (System.currentTimeMillis() - prevTokenTime > cietacToken.getExpires_in() * 1000) {
                cietacToken = null;
                initCietacToken();
            }
        }
    }
}
